package com.xl6667.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xl6667.domain.ResponseResult;
import com.xl6667.domain.entity.LoginUser;
import com.xl6667.domain.entity.User;
import com.xl6667.enums.AppHttpCodeEnum;
import com.xl6667.mapper.UserMapper;
import com.xl6667.service.AdminUserService;
import com.xl6667.util.JwtUtil;
import com.xl6667.util.RedisCache;
import com.xl6667.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
public class AdminUserServiceImpl extends ServiceImpl<UserMapper, User>
        implements AdminUserService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或吗密码有误");
        }
        //获取查询的用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取用户id
        String id = loginUser.getUser().getId().toString();
        //生成Jwt
        String jwt = JwtUtil.createJWT(id);
        //将用户信息存入redis
        redisCache.setCacheObject("admin:login"+id,loginUser);
        //封装token
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult logout() {
        //获取用户信息
        LoginUser loginUser = SecurityUtil.getLoginUser();
        //获取用户id
        String id = loginUser.getUser().getId().toString();
        //将用户信息从redis中删除;
        redisCache.deleteObject("admin:login"+id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
